package com.dwyinyuan.producer;

import com.dwyinyuan.enums.MeiZiEnums;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.concurrent.BlockingQueue;

/**
 * 防盗链问题还没解决
 */
public class MeiziProducer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public MeiziProducer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }


    @Override
    public void run() {
        try {
            Document document = Jsoup.connect(MeiZiEnums.xinggan.getUrl()).get();
            Elements elements = document.select("#pins a:has(img)");
            for (Element element : elements) {
                String detail = element.attr("href");
                Document detail_doc = Jsoup.connect(detail).get();

                String src = detail_doc.getElementsByClass("blur").first().attr("src");
                blockingQueue.put(src);

                String page = detail_doc.getElementsByClass("pagenavi").first()
                        .getElementsByTag("a").get(4).text();
                for (int i = 2; i < Integer.valueOf(page); i++) {
                    //https://www.mzitu.com/239844/2
                    String next = detail.concat("/" + i);
                    Document next_detail_doc = Jsoup.connect(next).get();
                    String next_src = next_detail_doc.getElementsByClass("blur").first().attr("src");
                    blockingQueue.put(next_src);
                    System.out.println(name + " 图片地址 ： " + next_src);
                }
            }
            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
